package com.chap6;

import java.util.concurrent.*;

/**
 * <p>
 * <code>CyclicBarrierDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-20 5:30
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5,()-> System.out.println("人齐了，准备发车"));
        for (int i = 0; i < 10; i++) {
            final int id = i+1;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(id+"号马上就到");
                    int sleepMils = ThreadLocalRandom.current().nextInt(2000);
                    try {
                        Thread.sleep(sleepMils);
                        System.out.println(id+"号到了，上车");
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }

                }
            });

        }

    }
}
